#include "stm32f10x.h"                  // Device header
#include "PWM.h"

//输出PWM波
void PWM_Init(void)
{
	//1.初始化TIM2，3还有GPIOA,B的时钟
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);  //定时器2用于控制电机
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);  //定时器3用于控制舵机
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); //输出电机的PWM波
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE); //输出舵机的PWM波
	
	//2.初始化GPIO的引脚
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出，只有在这个模式下，外设（PWM）才能控制引脚
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出，只有在这个模式下，外设（PWM）才能控制引脚
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;  //选择的是PB1
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB,&GPIO_InitStructure);
	
	//3.选择时基准单元的时钟（内部时钟）,gpio的引脚是挂在定时器通道上，所以要开启TIM3
	TIM_InternalClockConfig(TIM2);  //72Mhz
	TIM_InternalClockConfig(TIM3);  //72Mhz,实际是给定时器选择来源，选择的是内部时钟
	
	//4.配置时基单元
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
	TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInitStructure.TIM_Period = 100-1;   //ARR=100
	TIM_TimeBaseInitStructure.TIM_Prescaler = 36-1;   //PSC,预分频器
	TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0; 
	TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStructure);
	
	TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInitStructure.TIM_Period = 20000-1;   //舵机要求周期为20ms，那么PWM的频率应该为1/0.02 = 50HZ，PWM的频率为
	TIM_TimeBaseInitStructure.TIM_Prescaler = 72-1;   //PWM波的频率 = 时钟使能频率（72Mhz）/ARR/PSC = 72e6/2e4/72 = 50hz
	TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0; 
	TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStructure);
	
    //5.初始化输出比较单元
	TIM_OCInitTypeDef TIM_OCInitStructure;
	TIM_OCStructInit(&TIM_OCInitStructure); //赋初始值
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;//设置输出比较的模式
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;//设置输出比较的极性
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;//设置输出使能
	TIM_OCInitStructure.TIM_Pulse = 0;//设置CCR,不能超过ARR
	TIM_OC3Init(TIM2,&TIM_OCInitStructure);
	TIM_OC2Init(TIM2,&TIM_OCInitStructure);
	TIM_OC4Init(TIM3,&TIM_OCInitStructure);  //舵机使用的是定时器3的通道4
	
	//6.启动定时器
	TIM_Cmd(TIM2,ENABLE);
	TIM_Cmd(TIM3,ENABLE);
}
void PWM_SetCompare2(uint16_t Compare)
{
	TIM_SetCompare2(TIM2,Compare);   //设置CCR,不能超过ARR
	
}
void PWM_SetCompare3(uint16_t Compare)
{
	TIM_SetCompare3(TIM2,Compare);   //设置CCR,不能超过ARR
	
}
void PWM_SetCompare4(uint16_t Compare)
{
	TIM_SetCompare4(TIM3,Compare);   //设置舵机CCR,不能超过ARR
	
}
